package ynu.edu.user.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import ynu.edu.common.domain.DeductDTO;
import ynu.edu.common.domain.PageDTO;
import ynu.edu.common.domain.R;
import ynu.edu.user.domain.dto.LoginFormDTO;
import ynu.edu.user.domain.vo.UserLoginVO;
import ynu.edu.user.domain.vo.UserQuery;
import ynu.edu.user.domain.vo.UserVO;
import ynu.edu.user.service.IUserService;
import ynu.edu.common.exception.BadRequestException;

import javax.validation.Valid;

@Api(tags = "用户相关接口")
@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
@Slf4j
public class UserController {

    private final IUserService userService;

    @Value("${server.port}")
    private String port;

    @ApiOperation("用户登录接口")
    @PostMapping("login")
    public R<UserLoginVO> login(@RequestBody @Validated LoginFormDTO loginFormDTO){
        return userService.login(loginFormDTO);
    }

    @ApiOperation("用户注册接口")
    @PostMapping("/register")
    public R<String> register(@RequestBody @Validated LoginFormDTO loginFormDTO){
         return userService.register(loginFormDTO);
    }

    @ApiOperation("用户登出")
    @PostMapping("/logout")
    public R<Void> logout() {
        // 清除用户token
        userService.logout();
        return R.ok();
    }

    @ApiOperation("扣减余额")
    @ApiImplicitParam(name = "amount", value = "支付金额")
    @PutMapping("/money/deduct")
    public void deductMoney(@Valid @RequestBody DeductDTO deductDTO){
        Long userId = deductDTO.getUserId();
        Integer amount = deductDTO.getAmount();
        log.info("收到扣减余额请求，用户ID: {}, 金额: {}", userId, amount);
        
        // 参数验证
        if (amount == null || amount <= 0) {
            log.error("支付金额无效: {}", amount);
            throw new BadRequestException("支付金额必须大于0");
        }
        
        try {
            userService.deductMoney(userId,amount);
            log.info("扣减余额成功，用户ID: {}, 金额: {}", userId, amount);
        } catch (Exception e) {
            log.error("扣减余额失败，用户ID: {}, 金额: {}", userId, amount, e);
            throw e;
        }
    }

    @ApiOperation("分页查询用户")
    @GetMapping("/page")
    public R<PageDTO<UserVO>> queryUserByPage(UserQuery query) {
        return userService.queryUserByPage(query);
    }

    @ApiOperation("根据id查询用户")
    @GetMapping("/{id}")
    public R<UserVO> queryUserById(@PathVariable("id") Long id) {
        log.info("端口 {} 处理查询用户请求: id={}", port, id);
        return userService.queryUserById(id);
    }

    @ApiOperation("更新用户状态")
    @PutMapping("/{id}/status")
    public R<Void> updateUserStatus(@PathVariable("id") Long id, @RequestParam Integer status) {
        userService.updateUserStatus(id, status);
        return R.ok();
    }

    @PutMapping("/{id}")
    @ApiOperation("更新用户信息")
    public R<Void> updateUser(@PathVariable Long id, @RequestBody UserVO userVO) {
        userService.updateUser(id, userVO);
        return R.ok();
    }

}

